package com.reservation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reservation.common.BusinessException;
import com.reservation.entity.ArtCollection;
import com.reservation.entity.Exhibition;
import com.reservation.entity.ExhibitionCollection;
import com.reservation.mapper.CollectionMapper;
import com.reservation.mapper.ExhibitionCollectionMapper;
import com.reservation.mapper.ExhibitionMapper;
import com.reservation.service.CollectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 藏品服务实现类
 */
@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private ExhibitionMapper exhibitionMapper;

    @Autowired
    private ExhibitionCollectionMapper exhibitionCollectionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ArtCollection addCollection(ArtCollection artCollection) {
        // 设置创建时间和更新时间
        artCollection.setCreateTime(LocalDateTime.now());
        artCollection.setUpdateTime(LocalDateTime.now());

        // 保存藏品信息
        collectionMapper.insert(artCollection);
        ExhibitionCollection exhibitionCollection = new ExhibitionCollection();
        exhibitionCollection.setCollectionId(artCollection.getId());
        exhibitionCollection.setExhibitionId(artCollection.getExhibitionId());
        exhibitionCollectionMapper.insert(exhibitionCollection);

        return artCollection;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ArtCollection updateCollection(ArtCollection artCollection) {
        // 检查藏品是否存在
        ArtCollection existArtCollection = collectionMapper.selectById(artCollection.getId());
        if (existArtCollection == null) {
            throw new BusinessException("藏品不存在");
        }

        // 设置更新时间
        artCollection.setUpdateTime(LocalDateTime.now());

        // 更新藏品信息
        collectionMapper.updateById(artCollection);
        ExhibitionCollection exhibitionCollection = new ExhibitionCollection();
        exhibitionCollection.setCollectionId(artCollection.getId());
        exhibitionCollection.setExhibitionId(artCollection.getExhibitionId());
        exhibitionCollection.setId(exhibitionCollectionMapper.selectOne(new LambdaQueryWrapper<ExhibitionCollection>().eq(ExhibitionCollection::getCollectionId, artCollection.getId())).getId());
        exhibitionCollectionMapper.updateById(exhibitionCollection);
        // 返回更新后的藏品信息
        return collectionMapper.selectById(artCollection.getId());
    }

    @Override
    public ArtCollection getCollectionById(Long id) {
        ArtCollection artCollection = collectionMapper.selectById(id);
        if (artCollection == null) {
            throw new BusinessException("藏品不存在");
        }
        return artCollection;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCollection(Long id) {
        // 检查藏品是否存在
        ArtCollection artCollection = collectionMapper.selectById(id);
        if (artCollection == null) {
            throw new BusinessException("藏品不存在");
        }

        // 删除藏品与展览的关联
        LambdaQueryWrapper<ExhibitionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionCollection::getCollectionId, id);
        exhibitionCollectionMapper.delete(queryWrapper);

        // 删除藏品
        return collectionMapper.deleteById(id) > 0;
    }

    @Override
    public IPage<ArtCollection> getCollectionList(Page<ArtCollection> page, String name, String type, Integer exhibitionId) {
        LambdaQueryWrapper<ArtCollection> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(ArtCollection::getName, name);
        }
        if (StringUtils.isNotBlank(type)) {
            queryWrapper.eq(ArtCollection::getType, type);
        }
        if (exhibitionId != null) {
            // 查询与展览关联的藏品
            LambdaQueryWrapper<ExhibitionCollection> ecQueryWrapper = new LambdaQueryWrapper<>();
            ecQueryWrapper.eq(ExhibitionCollection::getExhibitionId, exhibitionId);
            List<ExhibitionCollection> relations = exhibitionCollectionMapper.selectList(ecQueryWrapper);
            if (!relations.isEmpty()) {
                List<Long> collectionIds = relations.stream()
                    .map(ExhibitionCollection::getCollectionId)
                    .collect(Collectors.toList());
                queryWrapper.in(ArtCollection::getId, collectionIds);
            } else {
                // 如果没有关联的藏品，返回空结果
                return new Page<>();
            }
        }
        // 按创建时间降序排序
        queryWrapper.orderByDesc(ArtCollection::getCreateTime);

        // 执行查询
        IPage<ArtCollection> result = collectionMapper.selectPage(page, queryWrapper);
        
        // 设置展览信息
        if (exhibitionId != null) {
            Exhibition exhibition = exhibitionMapper.selectById(exhibitionId);
            if (exhibition != null) {
                result.getRecords().forEach(collection -> {
                    collection.setExhibitionId((long) exhibitionId);
                });
            }
        }
        
        return result;
    }

    @Override
    public List<ArtCollection> getAllCollections() {
        LambdaQueryWrapper<ArtCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ArtCollection::getCreateTime);
        return collectionMapper.selectList(queryWrapper);
    }

    @Override
    public List<ArtCollection> getCollectionsByType(String type) {
        LambdaQueryWrapper<ArtCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArtCollection::getType, type);
        queryWrapper.orderByDesc(ArtCollection::getCreateTime);
        return collectionMapper.selectList(queryWrapper);
    }

    @Override
    public List<ArtCollection> getCollectionsByEra(String era) {
        LambdaQueryWrapper<ArtCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArtCollection::getEra, era);
        queryWrapper.orderByDesc(ArtCollection::getCreateTime);
        return collectionMapper.selectList(queryWrapper);
    }

    @Override
    public List<ArtCollection> getCollectionsByExhibition(Long exhibitionId) {
        // 检查展览是否存在
        if (exhibitionMapper.selectById(exhibitionId) == null) {
            throw new BusinessException("展览不存在");
        }

        // 查询展览关联的藏品ID
        LambdaQueryWrapper<ExhibitionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionCollection::getExhibitionId, exhibitionId);
        List<ExhibitionCollection> relations = exhibitionCollectionMapper.selectList(queryWrapper);

        if (relations.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取藏品ID列表
        List<Long> collectionIds = relations.stream()
                .map(ExhibitionCollection::getCollectionId)
                .collect(Collectors.toList());

        // 查询藏品信息
        LambdaQueryWrapper<ArtCollection> collectionQueryWrapper = new LambdaQueryWrapper<>();
        collectionQueryWrapper.in(ArtCollection::getId, collectionIds);
        return collectionMapper.selectList(collectionQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCollectionToExhibition(Long exhibitionId, Long collectionId) {
        // 检查展览是否存在
        if (exhibitionMapper.selectById(exhibitionId) == null) {
            throw new BusinessException("展览不存在");
        }

        // 检查藏品是否存在
        if (collectionMapper.selectById(collectionId) == null) {
            throw new BusinessException("藏品不存在");
        }

        // 检查关联是否已存在
        LambdaQueryWrapper<ExhibitionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionCollection::getExhibitionId, exhibitionId);
        queryWrapper.eq(ExhibitionCollection::getCollectionId, collectionId);
        if (exhibitionCollectionMapper.selectCount(queryWrapper) > 0) {
            return true; // 已存在关联，视为添加成功
        }

        // 创建关联
        ExhibitionCollection relation = new ExhibitionCollection();
        relation.setExhibitionId(exhibitionId);
        relation.setCollectionId(collectionId);
        relation.setCreateTime(LocalDateTime.now());

        return exhibitionCollectionMapper.insert(relation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCollectionFromExhibition(Long exhibitionId, Long collectionId) {
        // 检查展览是否存在
        if (exhibitionMapper.selectById(exhibitionId) == null) {
            throw new BusinessException("展览不存在");
        }

        // 检查藏品是否存在
        if (collectionMapper.selectById(collectionId) == null) {
            throw new BusinessException("藏品不存在");
        }

        // 删除关联
        LambdaQueryWrapper<ExhibitionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionCollection::getExhibitionId, exhibitionId);
        queryWrapper.eq(ExhibitionCollection::getCollectionId, collectionId);

        return exhibitionCollectionMapper.delete(queryWrapper) > 0;
    }
}